package com.iaiai.cobra.core.util;

import jakarta.servlet.http.HttpServletRequest;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created with IpUtil.
 * Package: com.iaiai.cobra.core.util
 * Author: iaiai
 * Create Time: 2024/7/30 21:58
 * QQ: 176291935
 * Email: 176291935@qq.com
 * Description:
 */
public class IpUtil {

    public static String getIpv4(HttpServletRequest request) throws UnknownHostException {
        String remoteAddr = request.getHeader("X-FORWARDED-FOR");
        if (remoteAddr == null || "".equals(remoteAddr)) {
            remoteAddr = request.getRemoteAddr();
        }

        InetAddress inetAddress = InetAddress.getByName(remoteAddr);
        if(inetAddress instanceof Inet4Address){
            return remoteAddr;
        }

        return null;
    }

}
